package com.huawei.codearts.tools.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class ResponseUtils {

    public static final int CODE_SUCCESS = 1000;
    public static final int CODE_ERROR = 1001;
    public static final String MESSAGE_SUCCESS = "success";

    /** ok 输出 */
    public static String ok() {
        return response(CODE_SUCCESS, MESSAGE_SUCCESS, new HashMap<>(), true);
    }

    /** error 输出 */
    public static String error(String message) {
        return response(CODE_ERROR, message, new HashMap<>(), false);
    }

    /** response 输出 */
    public static String response() {
        return response(CODE_SUCCESS, MESSAGE_SUCCESS, new HashMap<>());
    }

    /** response 输出 */
    public static String response(Object data) {
        return response(CODE_SUCCESS, MESSAGE_SUCCESS, data);
    }

    /** response 输出 */
    public static String response(int code, String msg) {
        return response(code, msg, new HashMap<>());
    }

    /** response 输出 */
    public static String response(int code, String msg, Object data) {
        return response(code, msg, data, true);
    }

    /** response 输出 */
    public static String response(int code, String msg, Object data, boolean success) {
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("code", code);
        map.put("msg", msg);
        map.put("success", success);
        map.put("data", data);
        try {
            return JsonUtils.mapToJson(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** log 输出 */
    public static String logException(Throwable e) {
        // 获取异常类名和异常信息
        String exceptionName = e.getClass().getName();
        String message = e.getMessage();

        // 获取异常栈轨迹中的文件名和方法名
        StackTraceElement[] stackTrace = e.getStackTrace();
        String fileName = stackTrace[0].getFileName();
        String methodName = stackTrace[0].getMethodName();
        String className = stackTrace[0].getClassName();
        int lineNumber = stackTrace[0].getLineNumber();

        // 记录日志
        log.info("[error][exception-name]:{}, [path]:{}, [line]:({}:{}), message:{}",
//                Thread.currentThread().getStackTrace()[2].getClassName(),
//                Thread.currentThread().getStackTrace()[2].getMethodName(),
                exceptionName,
                className+"."+methodName+"()",
                fileName,
                lineNumber,
                message);
        return ResponseUtils.error(message == null ? "error" : message);
    }

}
